package com.agileai.esb.smc.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.activation.DataHandler;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.domain.db.Column;
import com.agileai.esb.component.manager.ApplicationManager;
import com.agileai.esb.component.manager.LoggerManager;
import com.agileai.esb.component.manager.MessageFlowManager;
import com.agileai.esb.component.manager.PropertiesResourceManager;
import com.agileai.esb.component.manager.WebServiceManager;
import com.agileai.esb.core.SoakerContants;
import com.agileai.esb.helper.ZipHelper;
import com.agileai.esb.smc.bizmoduler.sysres.DbResourceManage;
import com.agileai.esb.smc.bizmoduler.sysres.MqContainerManage;
import com.agileai.esb.smc.bizmoduler.sysres.MqResourceManage;
import com.agileai.esb.smc.bizmoduler.sysres.SkAppManage;
import com.agileai.esb.smc.bizmoduler.tmp.TmpResourceManage;
import com.agileai.esb.smc.domain.Application;
import com.agileai.esb.smc.domain.DeployableZip;
import com.agileai.esb.smc.domain.MFFolder;
import com.agileai.esb.smc.domain.MFProfile;
import com.agileai.esb.smc.domain.MQObject;
import com.agileai.esb.smc.domain.MQResource;
import com.agileai.esb.smc.domain.ProcedureField;
import com.agileai.esb.smc.domain.PropertiesResource;
import com.agileai.esb.smc.domain.QueryField;
import com.agileai.esb.smc.domain.TmpResource;
import com.agileai.esb.smc.domain.TmpResourceGrp;
import com.agileai.esb.smc.domain.WSFolder;
import com.agileai.esb.smc.domain.WSProfile;
import com.agileai.esb.smc.servlet.SoakerDispatchServlet;
import com.agileai.esb.smc.util.SMCHelper;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.util.DBUtil;
import com.agileai.util.DateUtil;
import com.agileai.util.FileUtil;
import com.agileai.util.IOUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

public class SoakerManageImpl implements SoakerManage{
	public static final String NEW_LINE = "\r\n";
	public static Logger logger = LoggerManager.instance().getRootLogger();
	
	private SkAppManage skAppManage = null;
	
	public void setSkAppManage(SkAppManage skAppManage) {
		this.skAppManage = skAppManage;
	}
	
	public SkAppManage getSkAppManage() {
		return skAppManage;
	}
	
	public List<Application> findRawApplicationList(){
		List<Application> result = new ArrayList<Application>();
		List<DataRow> records = skAppManage.findRecords(new DataParam());
		if (records!=null){
			String appListURL = "http://localhost:"+SoakerDispatchServlet.getSoakerPort()+"/SMC/manager?actionType=list";
			String appListResponse = retrieveResponse(appListURL);
			List<String> activeList = new ArrayList<String>();
			if (appListResponse != null){
				String lineSpliter = System.getProperty("line.separator");
				String[] appInfos = appListResponse.split(lineSpliter);
				for (int i=0;i < appInfos.length;i++){
					String[] appInfo = appInfos[i].split(":");
					String tempAppName = appInfo[3];
					String appState = appInfo[1];
					if ("running".equals(appState)){
						activeList.add(tempAppName);
					}
				}
			}
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				Application application = new Application();
				String appName = row.stringValue("APP_NAME");
				String appAlias = row.stringValue("APP_ALIAS");
				application.setId(row.stringValue("APP_ID"));
				application.setName(appName);
				application.setAlias(appAlias);
				application.setDescription(row.stringValue("APP_DESC"));
				String deployed = row.stringValue("DEPLOYED");
				application.setDeployed("Y".equalsIgnoreCase(deployed));
				if (activeList.contains(appName)){
					application.setActive(true);
				}else{
					application.setActive(false);
				}
				result.add(application);
			}
		}
		return result;
	}
	
	public Application findRawApplication(String appName) {
		Application application = null;
		DataRow row = skAppManage.getRecord(new DataParam("APP_NAME",appName));
		if (!MapUtil.isNullOrEmpty(row)){
			application = new Application();
			application.setId(row.stringValue("APP_ID"));
			application.setName(row.stringValue("APP_NAME"));
			application.setAlias(row.stringValue("APP_ALIAS"));
			application.setDescription(row.stringValue("APP_DESC"));
			String deployed = row.stringValue("DEPLOYED");
			application.setDeployed("Y".equalsIgnoreCase(deployed));
		}
		return application;
	}

	public boolean createApplication(Application application) {
		try {
			DataParam dataParam = new DataParam();
			dataParam.put("APP_ID",application.getId());
			dataParam.put("APP_NAME",application.getName());
			dataParam.put("APP_ALIAS",application.getAlias());
			dataParam.put("DEPLOYED","N");
			dataParam.put("APP_MAINPKG",application.getMainPkg());
			dataParam.put("CREATE_SAMPLE",application.isCeateSample()?"Y":"N");
			dataParam.put("CREATE_USER",application.getCreateUser());
			dataParam.put("CREATE_TIME",new Date());
			skAppManage.createRecord(dataParam, application.getId());
			
			if (application.isCeateSample()) {
				DataParam replaceData = new DataParam();
				replaceData.put("9DCC5799-6002-48C0-90BF-F484FC0D9E28",application.getId());
				replaceData.put("2014-10-20 00:00:00", DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
				replaceData.put("com.aeai.video",application.getMainPkg());
				replaceData.put("admin",application.getCreateUser());
				replaceData.put("_VideoDemo_",application.getName());
				
				SMCHelper.executeSQLScript(replaceData);
			} else {
				DataParam mfParam = new DataParam();
				mfParam.put("FID",KeyGenerator.instance().genKey());
				mfParam.put("NAME","MF服务");
				mfParam.put("APP_ID",application.getId());
				mfParam.put("GROUP_TYPE","MF");
				
				DataParam wsParam = new DataParam();
				wsParam.put("FID",KeyGenerator.instance().genKey());
				wsParam.put("NAME","WS服务");
				wsParam.put("APP_ID",application.getId());
				wsParam.put("GROUP_TYPE","WS");
				
				skAppManage.insertTreeGroupRecord(wsParam);
				skAppManage.insertTreeGroupRecord(mfParam);
			}
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	
	public boolean deleteApplication(String appId) {
		try {
			DataParam deleteParam = new DataParam("APP_ID",appId);
			skAppManage.deletRecord(deleteParam);
			skAppManage.deleteTreeGroupRecords(appId);
			skAppManage.deleteMFProfileRecord(deleteParam);
			skAppManage.deleteWSProfileRecord(deleteParam);
			skAppManage.deleteWSProxyRecord(deleteParam);
			
			skAppManage.deletAuthRecords("APP", appId);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public Application retrieveApplication(String appId) {
		Application result = new Application();
		DataParam dataParam = new DataParam();
		dataParam.put("APP_ID",appId);
		DataRow basicDataRow = skAppManage.getRecord(dataParam);
		String deployed = basicDataRow.stringValue("DEPLOYED");
		if ("Y".equals(deployed)){
			List<DataRow> wsTreeGroupList = skAppManage.findTreeGroupRecords("WS", appId);
			List<DataRow> mfTreeGroupList = skAppManage.findTreeGroupRecords("MF", appId);
			
			List<DataRow> wsProfileList = skAppManage.findWSProfileRecords(appId);
			List<DataRow> mfProfileList = skAppManage.findMFProfileRecords(appId);
			
			this.initApplication(result, basicDataRow,wsTreeGroupList,mfTreeGroupList,wsProfileList,mfProfileList);
		}
		return result;
	}
	private void initApplication(Application app,DataRow row,List<DataRow> wsTreeGroupList,List<DataRow> mfTreeGroupList
			,List<DataRow> wsProfileList,List<DataRow> mfProfileList){
		boolean ceateSample = "Y".equals(row.stringValue("CREATE_SAMPLE"));
		String appName = row.stringValue("APP_NAME"); 
		app.setCeateSample(ceateSample);
		app.setId(row.stringValue("APP_ID"));
		app.setName(appName);
		app.setAlias(row.stringValue("APP_ALIAS"));
		app.setMainPkg(row.stringValue("APP_MAINPKG"));
		app.setDescription(row.stringValue("APP_DESC"));
		String deployed = row.stringValue("DEPLOYED");
		app.setDeployed("Y".equalsIgnoreCase(deployed));
		
		boolean isActive = SMCHelper.isActive(appName);
		app.setActive(isActive);
		
		if (isActive){
			String wsIdsURL = "http://localhost:"+SoakerDispatchServlet.getSoakerPort()
					+"/"+appName+"/services?actionType="+SoakerContants.ActionType.retrieveIds;
			String wsIds = retrieveResponse(wsIdsURL);
			wsIds = wsIds.replaceAll("\\r\\n", "");
			String[] wsIdArray = wsIds.split(",");
			if (wsIdArray != null){
				for (int i=0;i < wsIdArray.length;i++){
					String wsId = wsIdArray[i];
					app.getActiveWsIdList().add(wsId);
				}
			}
			
			String mfIdsURL = "http://localhost:"+SoakerDispatchServlet.getSoakerPort()
					+"/"+appName+"/messageflows?actionType="+SoakerContants.ActionType.retrieveIds;
			String mfIds = retrieveResponse(mfIdsURL);
			mfIds = mfIds.replaceAll("\\r\\n", "");
			String[] mfIdArray = mfIds.split(",");
			if (mfIdArray != null){
				for (int i=0;i < mfIdArray.length;i++){
					String mfId = mfIdArray[i];
					app.getActiveMfIdList().add(mfId);
				}
			}
		}
		
		HashMap<String,WSProfile> wsProfileContainer = new HashMap<String,WSProfile>();
		for (int i=0;i < wsTreeGroupList.size();i++){
			DataRow wsGroupRow = wsTreeGroupList.get(i);
			String parentId = wsGroupRow.getString("PARENTID");
			String name = wsGroupRow.getString("NAME");
			String id = wsGroupRow.getString("FID");
			if (parentId == null || parentId.trim().equals("")){
				WSFolder wsFolder = new WSFolder();
				wsFolder.setApplicationId(app.getId());
				wsFolder.setApplicationName(app.getName());
				wsFolder.setName(name);
				wsFolder.setId(id);
				app.getWsFolderList().add(wsFolder);
				this.initProfileList(app,wsFolder,wsProfileList,wsProfileContainer);
				this.loopInitWSFolder(app,wsFolder,wsTreeGroupList,wsProfileList,wsProfileContainer);
			}
		}
		
		for (int i=0;i < mfTreeGroupList.size();i++){
			DataRow mfGroupRow = mfTreeGroupList.get(i);
			String parentId = mfGroupRow.getString("PARENTID");
			String name = mfGroupRow.getString("NAME");
			String id = mfGroupRow.getString("FID");
			if (parentId == null || parentId.trim().equals("")){
				MFFolder mfFolder = new MFFolder();
				mfFolder.setApplicationId(app.getId());
				mfFolder.setApplicationName(app.getName());
				mfFolder.setName(name);
				mfFolder.setId(id);
				app.getMfFolderList().add(mfFolder);
				this.initProfileList(app,mfFolder,mfProfileList,wsProfileContainer);
				this.loopInitMFFolder(app,mfFolder,mfTreeGroupList,mfProfileList,wsProfileContainer);
			}
		}		
	}
	private void loopInitWSFolder(Application app,WSFolder wsFolder,List<DataRow> wsTreeGroupList,List<DataRow> wsProfileList,HashMap<String,WSProfile> wsProfileContainer){
		for (int i=0;i < wsTreeGroupList.size();i++){
			DataRow wsGroupRow = wsTreeGroupList.get(i);
			String parentId = wsGroupRow.getString("PARENTID");
			String name = wsGroupRow.getString("NAME");
			String fid = wsGroupRow.getString("FID");
			if (parentId != null && parentId.equals(wsFolder.getId())){
				WSFolder tempFolder = new WSFolder();
				tempFolder.setApplicationId(app.getId());
				tempFolder.setApplicationName(app.getName());
				tempFolder.setName(name);
				tempFolder.setId(fid);
				tempFolder.setParentId(parentId);
				this.initProfileList(app, tempFolder, wsProfileList,wsProfileContainer);
				wsFolder.getChildren().add(tempFolder);
				this.loopInitWSFolder(app, tempFolder, wsTreeGroupList, wsProfileList,wsProfileContainer);
			}
		}
	}
	private void initProfileList(Application app,WSFolder wsFolder,List<DataRow> wsProfileList,HashMap<String,WSProfile> wsProfileContainer){
		for (int i=0;i < wsProfileList.size();i++){
			DataRow wsDataRow = wsProfileList.get(i);
			String id = wsDataRow.getString("WS_ID");
			String wsGroup = wsDataRow.getString("WS_GROUP");
			String name = wsDataRow.getString("WS_NAME");
			String alias = wsDataRow.getString("WS_ALIAS");
			String deployed = wsDataRow.stringValue("DEPLOYED");
			
			if (wsGroup != null && wsGroup.equals(wsFolder.getId())){
				WSProfile wsProfile = new WSProfile();
				wsProfile.setApplicationId(app.getId());
				wsProfile.setApplicationName(app.getName());
				wsProfile.setId(id);
				wsProfile.setWsFolderId(wsGroup);
				wsProfile.setName(name);
				wsProfile.setAlias(alias);
				if ("Y".equalsIgnoreCase(deployed)){
					app.getDeployedWsIdList().add(id);
				}
				wsProfileContainer.put(id, wsProfile);
				wsFolder.getWsProfileList().add(wsProfile);
			}
		}
	}


	private void loopInitMFFolder(Application app,MFFolder wsFolder,List<DataRow> wsTreeGroupList,List<DataRow> wsProfileList,HashMap<String,WSProfile> wsProfileContainer){
		for (int i=0;i < wsTreeGroupList.size();i++){
			DataRow wsGroupRow = wsTreeGroupList.get(i);
			String parentId = wsGroupRow.getString("PARENTID");
			String name = wsGroupRow.getString("NAME");
			String id = wsGroupRow.getString("FID");
			if (parentId != null && parentId.equals(wsFolder.getId())){
				MFFolder tempFolder = new MFFolder();
				tempFolder.setApplicationId(app.getId());
				tempFolder.setApplicationName(app.getName());
				tempFolder.setName(name);
				tempFolder.setParentId(parentId);
				tempFolder.setId(id);
				this.initProfileList(app, tempFolder, wsProfileList,wsProfileContainer);
				wsFolder.getChildren().add(tempFolder);
				this.loopInitMFFolder(app, tempFolder, wsTreeGroupList, wsProfileList,wsProfileContainer);
			}
		}
	}
	private void initProfileList(Application app,MFFolder mfFolder,List<DataRow> mfProfileList,HashMap<String,WSProfile> wsProfileContainer){
		for (int i=0;i < mfProfileList.size();i++){
			DataRow mfDataRow = mfProfileList.get(i);
			String id = mfDataRow.getString("MF_ID");
			String mfGroup = mfDataRow.getString("MF_GROUP");
			String mfType = mfDataRow.getString("MF_TYPE");
			String name = mfDataRow.getString("MF_NAME");
			String alias = mfDataRow.getString("MF_ALIAS");
			String deployed = mfDataRow.stringValue("DEPLOYED");
			String shareLog = mfDataRow.stringValue("SHARELOG");
			String wsId = mfDataRow.getString("WS_ID");
			if (mfGroup != null && mfGroup.equals(mfFolder.getId())){
				MFProfile mfProfile = new MFProfile();
				mfProfile.setApplicationId(app.getId());
				mfProfile.setApplicationName(app.getName());
				mfProfile.setId(id);
				mfProfile.setMfFolderId(mfGroup);
				mfProfile.setType(mfType);
				mfProfile.setName(name);
				mfProfile.setShareLog("Y".equals(shareLog));
				mfProfile.setAlias(alias);
				
				if ("Y".equalsIgnoreCase(deployed)){
					app.getDeployedMfIdList().add(id);
				}
				if (StringUtil.isNotNullNotEmpty(wsId)){
					WSProfile wsProfile = (WSProfile)wsProfileContainer.get(wsId);
					if (wsProfile != null){
						wsProfile.getMfIdList().add(id);
					}
				}
				mfFolder.getMfProfileList().add(mfProfile);
			}
		}
	}
	
	public boolean createWebServiceProfile(WSProfile wsProfile) {
		try {
			DataParam param = new DataParam();
			param.put("WS_ID",wsProfile.getId());
			param.put("APP_ID",wsProfile.getApplicationId());
			param.put("WS_GROUP",wsProfile.getWsFolderId());
			param.put("WS_NAME",wsProfile.getName());
			param.put("WS_ALIAS",wsProfile.getAlias());
			param.put("DEPLOYED","N");
			param.put("WS_ADDRESS","/"+wsProfile.getName());
			param.put("WS_IMPL_CLASS",wsProfile.getImplClass());
//			param.put("MF_PATH","N");
//			param.put("MF_DESC","N");
			param.put("CREATE_USER",wsProfile.getCreateUser());
			param.put("CREATE_TIME",new Date());
			skAppManage.insertWSProfileRecord(param);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	public boolean deleteWebServiceProfile(String appId,String serviceId) {
		try {
			DataParam param = new DataParam("WS_ID",serviceId,"APP_ID",appId);
			skAppManage.deleteWSProfileRecord(param);
			
			skAppManage.deletAuthRecords("MF", appId+serviceId);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	public boolean createMessageFlowProfile(MFProfile mfProfile) {
		try {
			DataParam param = new DataParam();
			param.put("MF_ID",mfProfile.getId());
			param.put("APP_ID",mfProfile.getApplicationId());
			param.put("MF_GROUP",mfProfile.getMfFolderId());
			param.put("MF_TYPE",mfProfile.getType());
			param.put("MF_NAME",mfProfile.getName());
			param.put("MF_ALIAS",mfProfile.getAlias());
			param.put("DEPLOYED","N");
			param.put("SHARELOG","Y");
			param.put("START_WITH_SERVER","Y");
			
//			param.put("MF_PATH","N");
//			param.put("MF_DESC","N");
			param.put("CREATE_USER",mfProfile.getCreateUser());
			param.put("CREATE_TIME",new Date());
			param.put("WS_ID",mfProfile.getWsId());
			skAppManage.insertMFProfileRecord(param);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	public boolean deleteMessageFlowProfile(String appId,String mfProfileId) {
		try {
			DataParam param = new DataParam();
			param.put("MF_ID",mfProfileId,"APP_ID",appId);
			skAppManage.deleteMFProfileRecord(param);
			
			skAppManage.deletAuthRecords("MF", appId+mfProfileId);
			
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	
	public boolean moveMessageFlowProfiles(String appId,String messageFlowId,String targetFolderId){
		boolean result = false;
		try {
			skAppManage.moveMessageFlowProfiles(appId, messageFlowId, targetFolderId);
			result = true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}

	public boolean createWebServiceFolder(WSFolder wsFolder) {
		try {
			DataParam param = new DataParam();
			param.put("FID",wsFolder.getId());
			param.put("NAME",wsFolder.getName());
			param.put("APP_ID",wsFolder.getApplicationId());
			param.put("GROUP_TYPE","WS");
			param.put("PARENTID",wsFolder.getParentId());
			skAppManage.insertTreeGroupRecord(param);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean updateWebServiceFolder(WSFolder wsFolder) {
		try {
			skAppManage.updateTreeGroupRecord(wsFolder.getId(),wsFolder.getName());
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean deleteWebServiceFolder(String appId,String wsFolderId) {
		try {
			skAppManage.deleteTreeGroupRecord(appId,wsFolderId);
			skAppManage.deletAuthRecords("FOLDER", appId+wsFolderId);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean createMessageFlowFolder(MFFolder mfFolder) {
		try {
			DataParam param = new DataParam();
			param.put("FID",mfFolder.getId());
			param.put("NAME",mfFolder.getName());
			param.put("APP_ID",mfFolder.getApplicationId());
			param.put("GROUP_TYPE","MF");
			param.put("PARENTID",mfFolder.getParentId());
			skAppManage.insertTreeGroupRecord(param);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}

	}

	public boolean updateMessageFlowFolder(MFFolder mfFolder) {
		try {
			skAppManage.updateTreeGroupRecord(mfFolder.getId(),mfFolder.getName());
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean deleteMessageFlowFolder(String appId,String mfFolderId) {
		try {
			skAppManage.deleteTreeGroupRecord(appId,mfFolderId);
			skAppManage.deletAuthRecords("FOLDER", appId+mfFolderId);
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean deployApplication(DeployableZip appZip) {
		DataHandler dataHandler = appZip.getDataHandler();
		try {
			String appName = appZip.getName();
			logger.info("deploy Application "+ appName +" ......");
			
			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			File appDir = new File(appPath);
			if (!appDir.exists()){
				appDir.mkdirs();		
			}
			
			InputStream is = dataHandler.getInputStream();
			String tempDeploy = SoakerDispatchServlet.getToDeployPath();
			File deployDir = new File(tempDeploy);
			if (!deployDir.exists()){
				deployDir.mkdirs();
			}
			String curAppZipFile = tempDeploy + "/" + appName+".zip";
			File curAppZip = new File(curAppZipFile);
			if (!curAppZip.exists()){
				curAppZip.createNewFile();
			}
            OutputStream os = new FileOutputStream(curAppZip);
            IOUtil.copy(is, os);
            is.close();
            os.close();

            String soakerAppZipFile = SoakerDispatchServlet.getReponsitoryPath() + "/ESBApp.zip";
            ZipHelper zipHelper = new ZipHelper();
            zipHelper.unZip(soakerAppZipFile, appDir.getAbsolutePath());
            zipHelper.unZip(curAppZipFile, appDir.getAbsolutePath()+"/WEB-INF");
            
	        DataParam updateParam = new DataParam("APP_ID",appZip.getId(),"DEPLOYED","Y","APP_ALIAS",appZip.getAlias());
	        String operator = appZip.getOperator();
	        updateParam.put("DEPLOY_USER",operator,"DEPLOY_TIME",new Date());
	        skAppManage.updateAppDeploySetting(updateParam);
	        
	        logger.info("deploy Application "+ appName +" successfully !");
            return true;
		} catch (IOException e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean undeployApplication(String appName) {
		try {
			logger.info("undeploy Application "+ appName +" ......");
			
			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			File appDir = new File(appPath);
			if (appDir.exists()){
				FileUtil.deleteDir(appDir);
			}
	        DataParam updateParam = new DataParam("APP_NAME",appName,"DEPLOYED","N");
	        skAppManage.updateAppDeploySetting(updateParam);
			
	        logger.info("undeploy Application "+ appName +" successfully !");
	        return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean startApplication(String appName) {
		boolean result =false;
		StringWriter buffer = new StringWriter();
		String dataURL = null;
		dataURL = "http://localhost:"+ SoakerDispatchServlet.getSoakerPort() + "/SMC/manager?actionType=start&path="+appName;
		try {
			logger.info("start Application "+ appName +" ......");
			
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			if (buffer.toString().startsWith("OK")){
				result = true;
				logger.info("start Application "+ appName +" successfully !");
			}else{
				logger.info("start Application "+ appName +" failed !");
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}

	private void removeWS8MFCache(String appName){
		ApplicationManager applicationManager = ApplicationManager.instance(appName);
		DataRow row = applicationManager.getApplication();
		String appId = row.stringValue("APP_ID");
		MessageFlowManager messageFlowManager = MessageFlowManager.instance(appName);
		List<DataRow> mfRecords = skAppManage.findMFProfileRecords(appId);
		for (int i =0;i < mfRecords.size();i++){
			DataRow mfRow = mfRecords.get(i);
			String messageFlowId = mfRow.stringValue("MF_ID");
			if (messageFlowManager.isActive(messageFlowId)){
				messageFlowManager.removeFlowConfig(messageFlowId);					
			}
		}
		WebServiceManager webServiceManager = WebServiceManager.instance(appName);
		List<DataRow> wsRecords = skAppManage.findWSProfileRecords(appId);
		for (int i=0;i < wsRecords.size();i++){
			DataRow wsRow = wsRecords.get(i);
			String wsId = wsRow.stringValue("WS_ID");
			if (webServiceManager.isActive(wsId)){
				webServiceManager.getEndpoints().remove(wsId);
			}
		}
	}
	
	private void unloadTimer8QueueMessageFlows(String appName){
		StringWriter buffer = new StringWriter();
		String dataURL = "http://localhost:"+ SoakerDispatchServlet.getSoakerPort() + "/"+appName +"/messageflows?actionType=unloadAll";
		try {
			logger.info("unloadTimer8QueueMessageFlows "+ appName +" ......");
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			
			logger.info("unloadTimer8QueueMessageFlows "+ appName +" successfully !");
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
	}
	
	public boolean stopApplication(String appName) {
		boolean result =false;
		StringWriter buffer = new StringWriter();
		String dataURL = "http://localhost:"+ SoakerDispatchServlet.getSoakerPort() + "/SMC/manager?actionType=stop&path="+appName;
		try {
			logger.info("stop Application "+ appName +" ......");
			
			this.unloadTimer8QueueMessageFlows(appName);
			
			this.removeWS8MFCache(appName);
			
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			
			if (buffer.toString().startsWith("OK")){
				result = true;
				logger.info("stop Application "+ appName +" successfully !");
			}else{
				logger.info("stop Application "+ appName +" failed !");
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}

	public boolean deployWebServiceProfile(String appName,
			DeployableZip webServiceZip, List<DeployableZip> messageFlowZipList) {
		try {
			String wsName = webServiceZip.getName();
			logger.info("deploy WebService "+ wsName +" ......");
			DataHandler dataHandler = webServiceZip.getDataHandler();
			InputStream is = dataHandler.getInputStream();
			String tempDeploy = SoakerDispatchServlet.getToDeployPath();
			File deployDir = new File(tempDeploy);
			if (!deployDir.exists()){
				deployDir.mkdirs();
			}
			String curAppZipFile = tempDeploy + "/" + wsName+".zip";
			File curAppZip = new File(curAppZipFile);
			if (!curAppZip.exists()){
				curAppZip.createNewFile();
			}
	        OutputStream os = new FileOutputStream(curAppZip);
	        IOUtil.copy(is, os);
	        is.close();
	        os.close();
	
			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			File appDir = new File(appPath);
	        ZipHelper zipHelper = new ZipHelper();
			DataParam param = new DataParam("APP_NAME",appName);
			DataRow row = this.skAppManage.getRecord(param);
			String mainPkg = row.getString("APP_MAINPKG");
			String mainPkgPath = mainPkg.replaceAll("\\.", "/");
	        String mfPath = appDir.getAbsolutePath()+"/WEB-INF/services/"+mainPkgPath+"/services/"+wsName.toLowerCase();
	        
	        File mfDir = new File(mfPath);
	        if (!mfDir.exists()){
	        	mfDir.mkdirs();
	        }
	        zipHelper.unZip(curAppZipFile, mfPath);		
	        
	        DataParam updateParam = new DataParam("WS_ID",webServiceZip.getId(),"DEPLOYED","Y","WS_ALIAS",webServiceZip.getAlias());
	        String operator = webServiceZip.getOperator();
	        updateParam.put("DEPLOY_USER",operator,"DEPLOY_TIME",new Date());
	        String version = webServiceZip.getVersion();
	        String description = webServiceZip.getDescription();
	        updateParam.put("WS_VERSION",version,"WS_DESC",description);
	        
	        skAppManage.updateWSDeploySetting(updateParam);
	        
	        logger.info("deploy WebService "+ wsName +" successfully !");
	        return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}        
		return false;
	}

	public boolean undeployWebServiceProfile(String appName, String webServiceName,String webServiceId) {
		try {
			logger.info("undeploy WebService "+ webServiceName +" ......");
			
			DataParam param = new DataParam("APP_NAME",appName);
			DataRow row = this.skAppManage.getRecord(param);
			String mainPkg = row.getString("APP_MAINPKG");
			String mainPkgPath = mainPkg.replaceAll("\\.", "/");
			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			String serviceDir = appPath+"/WEB-INF/services/"+mainPkgPath+"/services/"+webServiceName.toLowerCase();
			File serviceDirlFile = new File(serviceDir);
			if (serviceDirlFile.isDirectory() && serviceDirlFile.exists()){
				FileUtil.deleteDir(serviceDirlFile);
			}
	        DataParam updateParam = new DataParam("WS_ID",webServiceId,"DEPLOYED","N");
	        skAppManage.updateWSDeploySetting(updateParam);
	        
	        logger.info("undeploy WebService "+ webServiceName +" successfully !");
			return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean startWebServiceProfile(String appName, String webServiceName) {
		logger.info("start WebService "+ webServiceName +" ......");
		boolean result = this.processWebServiceProfile(appName, webServiceName,SoakerContants.ActionType.publish);
		if (result){
			logger.info("start WebService "+ webServiceName +" successfully !");			
		}else{
			logger.info("start WebService "+ webServiceName +" failed !");
		}
		return result;
	}

	public boolean stopWebServiceProfile(String appName, String webServiceName) {
		logger.info("stop WebService "+ webServiceName +" ......");
		boolean result = this.processWebServiceProfile(appName, webServiceName,SoakerContants.ActionType.unload);
		if (result){
			logger.info("stop WebService "+ webServiceName +" successfully !");			
		}else{
			logger.info("stop WebService "+ webServiceName +" failed !");
		}
		return result;
	}

	public boolean deployMessageFlowProfile(String appName,
			DeployableZip messageFlowZip) {
		try {
			String mfName = messageFlowZip.getName();
			logger.info("deploy MessageFlow "+ mfName +" ......");
			
			DataHandler dataHandler = messageFlowZip.getDataHandler();
			InputStream is = dataHandler.getInputStream();
			String tempDeploy = SoakerDispatchServlet.getToDeployPath();
			File deployDir = new File(tempDeploy);
			if (!deployDir.exists()){
				deployDir.mkdirs();
			}
			String curAppZipFile = tempDeploy + "/" + mfName+".zip";
			File curAppZip = new File(curAppZipFile);
			if (!curAppZip.exists()){
				curAppZip.createNewFile();
			}
	        OutputStream os = new FileOutputStream(curAppZip);
	        IOUtil.copy(is, os);
	        is.close();
	        os.close();

			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			File appDir = new File(appPath);
	        ZipHelper zipHelper = new ZipHelper();
			DataParam param = new DataParam("APP_NAME",appName);
			DataRow row = this.skAppManage.getRecord(param);
			String mainPkg = row.getString("APP_MAINPKG");
			String mainPkgPath = mainPkg.replaceAll("\\.", "/");
	        String mfPath = appDir.getAbsolutePath()+"/WEB-INF/messageflows/"+mainPkgPath+"/messageflows/"+mfName.toLowerCase();
	        
	        File mfDir = new File(mfPath);
	        if (!mfDir.exists()){
	        	mfDir.mkdirs();
	        }
	        zipHelper.unZip(curAppZipFile, mfPath);
	        String shareLog = messageFlowZip.isShareLog()?"Y":"N";
	        DataParam updateParam = new DataParam("MF_ID",messageFlowZip.getId(),"DEPLOYED","Y","SHARELOG",shareLog,"MF_ALIAS",messageFlowZip.getAlias());
	        String operator = messageFlowZip.getOperator();
	        updateParam.put("DEPLOY_USER",operator,"DEPLOY_TIME",new Date());
	        String description = messageFlowZip.getDescription();
	        updateParam.put("MF_DESC",description);
	        skAppManage.updateMFDeploySetting(updateParam);
	        
	        logger.info("deploy MessageFlow "+ mfName +" successfully !");
	        return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}

	public boolean undeployMessageFlowProfile(String appName,String messageFlowName,String messageFlowId) {
		try {
			logger.info("undeploy MessageFlow "+ messageFlowName +" ......");
			
			DataParam param = new DataParam("APP_NAME",appName);
			DataRow row = this.skAppManage.getRecord(param);
			String mainPkg = row.getString("APP_MAINPKG");
			String mainPkgPath = mainPkg.replaceAll("\\.", "/");
			String appPath = SoakerDispatchServlet.getApplicationPath(appName);
			String mfPath = appPath+"/WEB-INF/messageflows/"+mainPkgPath+"/messageflows/"+messageFlowName.toLowerCase();
			File mfDir = new File(mfPath);
			if (mfDir.exists()){
				FileUtil.removeDir(mfDir);
			}
	        DataParam updateParam = new DataParam("MF_ID",messageFlowId,"DEPLOYED","N");
	        skAppManage.updateMFDeploySetting(updateParam);
			
	        logger.info("undeploy MessageFlow "+ messageFlowName +" successfully !");
	        return true;
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return false;
		}
	}
	
	private boolean processWebServiceProfile(String appName, String wsName,String operationType) {
		boolean result = false;
		StringWriter buffer = new StringWriter();
		String dataURL = null;
		dataURL = "http://localhost:"+ SoakerDispatchServlet.getSoakerPort() + "/"+appName
				+"/services?actionType="+operationType+"&wsName="+wsName;
		try {
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			if (SoakerContants.Success.equals(buffer.toString())){
				result = true;
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	private boolean processMessageFlowProfile(String appName, String messageFlowName,String operationType) {
		boolean result = false;
		StringWriter buffer = new StringWriter();
		String dataURL = null;
		dataURL = "http://localhost:"+ SoakerDispatchServlet.getSoakerPort() + "/"+appName
				+"/messageflows?actionType="+operationType+"&mfName="+messageFlowName;
		try {
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			if (SoakerContants.Success.equals(buffer.toString())){
				result = true;
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	private Connection getConnection(String datasourceName){
		Connection result = null;
		if (!datasourceName.startsWith("proxool.")){
			datasourceName = "proxool."+datasourceName;
		}
		try {
			Connection temp = DriverManager.getConnection(datasourceName);;
			result = temp;
		} catch (SQLException e) {
			logger.error(e.getLocalizedMessage(),e);
		}			
		return result;
	}
	
	private String retrieveResponse(String dataURL){
		String result= "";
		StringWriter buffer = new StringWriter();
		try {
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			result = buffer.toString();
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	public boolean startMessageFlowProfile(String appName,String messageFlowName) {
		logger.info("start MessageFlow "+ messageFlowName +" ......");
		boolean result = processMessageFlowProfile(appName, messageFlowName, SoakerContants.ActionType.publish);
		if (result){
			logger.info("start MessageFlow "+ messageFlowName +" successfully !");			
		}else{
			logger.info("start MessageFlow "+ messageFlowName +" failed !");
		}
		return result;
	}

	public boolean stopMessageFlowProfile(String appName,String messageFlowName) {
		logger.info("stop MessageFlow "+ messageFlowName +" ......");
		boolean result = processMessageFlowProfile(appName, messageFlowName, SoakerContants.ActionType.unload);
		if (result){
			logger.info("stop MessageFlow "+ messageFlowName +" successfully !");			
		}else{
			logger.info("stop MessageFlow "+ messageFlowName +" failed !");
		}
		return result;
	}

	@Override
	public boolean isDuplicateApplicationName(String appName) {
		boolean result = false;
		List<DataRow> records = skAppManage.findRecords(new DataParam());
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempName = row.getString("APP_NAME");
				if (appName.equalsIgnoreCase(tempName)){
					result = true;
					break;
				}
			}
		}
		return result;
	}

	@Override
	public boolean isDuplicateWebServiceName(String appId, String wsName) {
		boolean result = false;
		List<DataRow> records = skAppManage.findWSProfileRecords(appId);
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempName = row.getString("WS_NAME");
				if (wsName.equalsIgnoreCase(tempName)){
					result = true;
					break;
				}
			}
		}
		return result;
	}

	@Override
	public boolean isDuplicateWebServiceFolderName(String appId,
			String wsFolderName) {
		boolean result = false;
		List<DataRow> records = skAppManage.findTreeGroupRecords("WS", appId);
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempName = row.getString("NAME");
				if (wsFolderName.equalsIgnoreCase(tempName)){
					result = true;
					break;
				}
			}
		}
		return result;
	}

	@Override
	public boolean isDuplicateMessageFlowName(String appId, String mfName) {
		boolean result = false;
		List<DataRow> records = skAppManage.findMFProfileRecords(appId);
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempName = row.getString("MF_NAME");
				if (mfName.equalsIgnoreCase(tempName)){
					result = true;
					break;
				}
			}
		}
		return result;
	}

	@Override
	public boolean isDuplicateMessageFlowFolderName(String appId,
			String mfFolderName) {
		boolean result = false;
		List<DataRow> records = skAppManage.findTreeGroupRecords("MF", appId);
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempName = row.getString("NAME");
				if (mfFolderName.equalsIgnoreCase(tempName)){
					result = true;
					break;
				}
			}
		}
		return result;
	}
	
	public List<String> findDatabaseList() {
		List<String> result = new ArrayList<String>();
		DbResourceManage service = (DbResourceManage)BeanFactory.instance().getBean("dbResourceManageService");
		List<DataRow> records = service.findRecords(new DataParam());
		if (records != null){
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String databseName = row.stringValue("DB_ALIAS");
				result.add(databseName);
			}
		}
		return result;
	}
	
	@Override
	public List<String> findTableList(String dbResourceName) {
		List<String> result = null;
		
		DbResourceManage service = (DbResourceManage)BeanFactory.instance().getBean("dbResourceManageService");
		DataRow row = service.getRecord(new DataParam("DB_ALIAS",dbResourceName));
//		B_ID,DB_NAME,DB_ALIAS,DB_DESC,DB_URL,DB_DRIVER,DB_USER,DB_PWD,DB_TESTSQL,DB_MAXCONN,DB_IDLECONN,DB_PROPERTIES
		String dbUser = row.stringValue("DB_USER");
		String dbURL = row.stringValue("DB_URL");
		String datasourceName = row.stringValue("DB_ALIAS");
		Connection connection = getConnection(datasourceName);
		try {
			if (dbURL.toLowerCase().indexOf("oracle") > -1){
				result = DBUtil.getTables(dbUser, connection);
			}else{
				result = DBUtil.getTables(null, connection);			
			}			
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		
		return result;
	}
	
	
	@Override
	public List<String> findViewList(String databaseName) {
		List<String> result = null;
		
		DbResourceManage service = (DbResourceManage)BeanFactory.instance().getBean("dbResourceManageService");
		DataRow row = service.getRecord(new DataParam("DB_ALIAS",databaseName));
//		B_ID,DB_NAME,DB_ALIAS,DB_DESC,DB_URL,DB_DRIVER,DB_USER,DB_PWD,DB_TESTSQL,DB_MAXCONN,DB_IDLECONN,DB_PROPERTIES
		String dbUser = row.stringValue("DB_USER");
		String dbURL = row.stringValue("DB_URL");
		String datasourceName = row.stringValue("DB_ALIAS");
		Connection connection = getConnection(datasourceName);
		try {
			if (dbURL.toLowerCase().indexOf("oracle") > -1){
				result = DBUtil.getViews(dbUser, connection);
			}else{
				result = DBUtil.getViews(null, connection);			
			}			
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		
		return result;
	}

	@Override
	public List<String> findProcedureList(String databaseName) {
		List<String> result = null;
		
		DbResourceManage service = (DbResourceManage)BeanFactory.instance().getBean("dbResourceManageService");
		DataRow row = service.getRecord(new DataParam("DB_ALIAS",databaseName));
//		B_ID,DB_NAME,DB_ALIAS,DB_DESC,DB_URL,DB_DRIVER,DB_USER,DB_PWD,DB_TESTSQL,DB_MAXCONN,DB_IDLECONN,DB_PROPERTIES
		String dbUser = row.stringValue("DB_USER");
		String dbURL = row.stringValue("DB_URL");
		String datasourceName = row.stringValue("DB_ALIAS");
		Connection connection = getConnection(datasourceName);
		try {
			if (dbURL.toLowerCase().indexOf("oracle") > -1){
				result = DBUtil.getProcedures(dbUser, connection);
			}else{
				result = DBUtil.getProcedures(null, connection);			
			}			
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		
		return result;
	}	
	
	@Override
	public List<ProcedureField> retrieveProcedureFieldList(String databaseName,
			String procedureName) {
		List<ProcedureField> result = new ArrayList<ProcedureField>();
		DbResourceManage service = (DbResourceManage)BeanFactory.instance().getBean("dbResourceManageService");
		DataRow row = service.getRecord(new DataParam("DB_ALIAS",databaseName));
//		B_ID,DB_NAME,DB_ALIAS,DB_DESC,DB_URL,DB_DRIVER,DB_USER,DB_PWD,DB_TESTSQL,DB_MAXCONN,DB_IDLECONN,DB_PROPERTIES
		String dbUser = row.stringValue("DB_USER");
		String dbURL = row.stringValue("DB_URL");
		String datasourceName = row.stringValue("DB_ALIAS");
		Connection connection = getConnection(datasourceName);
		try {
			List<Column> columns = null;
			if (dbURL.toLowerCase().indexOf("oracle") > -1){
				columns = DBUtil.getProcedureColumns(dbUser, procedureName, connection);
			}else{
				columns = DBUtil.getProcedureColumns(null,procedureName,connection);			
			}
			if (columns != null && columns.size() > 0){
				for (int i=0;i < columns.size();i++){
					Column column = columns.get(i);
					ProcedureField procedureField = new ProcedureField();
					procedureField.setFieldName(column.getName());
					procedureField.setClassType(column.getClassName());
					procedureField.setFieldType(column.getParamType());
					procedureField.setSqlType(column.getType());
					result.add(procedureField);
				}
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		return result;
	}
	
	@Override
	public String retrieveQueryTableSQL(String dbResourceName,String tableName) {
		String result = null;
		Connection connection = getConnection(dbResourceName);
		try {
			Column[] columns = DBUtil.getColumns(tableName, connection);
			StringBuffer sql = new StringBuffer();
			if (columns != null){
				sql.append("select ");
				for (int i=0;i < columns.length;i++){
					Column column = columns[i];
					String fieldName = column.getName();
					sql.append(fieldName);
					if (i < columns.length-1){
						sql.append(",");
					}
				}
				sql.append(NEW_LINE);
				sql.append("from ").append(tableName);
				result = sql.toString();
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		return result;
	}
	
	@Override
	public List<QueryField> retrieveQueryFieldList(String databaseName,String sql){
		List<QueryField> result = new ArrayList<QueryField>();
		Connection connection = getConnection(databaseName);
		try {
			Column[] columns = DBUtil.getColumnsBySQL(sql,connection);
			if (columns != null){
				for (int i=0;i < columns.length;i++){
					Column column = columns[i];
					QueryField queryField = new QueryField();
					queryField.setClassType(column.getClassName());
					queryField.setFieldName(column.getName());
					queryField.setSqlType(column.getType());
					result.add(queryField);
				}
			}	
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			e.printStackTrace();
		}finally{
			DBUtil.close(connection);
		}
		return result;
	}
	
	public List<MQResource> findRawMessageQRourceList() {
		List<MQResource> result = new ArrayList<MQResource>();
		MqResourceManage mqResourceManage = (MqResourceManage)BeanFactory.instance().getBean("mqResourceManageService");
		List<DataRow> records = mqResourceManage.findRecords(new DataParam());
		if (records != null && records.size() > 0){
			for (int i=0;i < records.size();i++){
				DataRow row = (DataRow)records.get(i);
				MQResource mqResource = new MQResource();
				mqResource.setId(row.stringValue("BROKER_ID"));
				mqResource.setName(row.stringValue("BROKER_NAME"));
				mqResource.setUserName(row.stringValue("BROKER_USER"));
				mqResource.setUserPwd(row.stringValue("BROKER_PWD"));
				mqResource.setUrl(row.stringValue("BROKER_URL"));
				result.add(mqResource);
			}
		}
		return result;
	}
	
	public MQResource retrieveMessageQRource(String mqResourceName) {
//		select c.CONTAINER_ID,c.BROKER_ID,c.CONTAINER_NAME,c.CONTAINER_ALIAS,c.CONTAINER_TYPE,c.CONTAINER_DESC,c.CONTAINER_PROPERTIES 
//		,r.BROKER_NAME,r.BROKER_ALIAS,r.BROKER_USER,r.BROKER_PWD,r.BROKER_URL
		MQResource result = null;
		MqContainerManage mqContainerManage = (MqContainerManage)BeanFactory.instance().getBean("mqContainerManageService");
		List<DataRow> records = mqContainerManage.findRecords(new DataParam("brokerName",mqResourceName));
		if (records != null && records.size() > 0){
			result = new MQResource();
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				if (i == 0){
					result.setId(row.stringValue("BROKER_ID"));
					result.setName(row.stringValue("BROKER_NAME"));
					result.setUserName(row.stringValue("BROKER_USER"));
					result.setUserPwd(row.stringValue("BROKER_PWD"));
					result.setUrl(row.stringValue("BROKER_URL"));
				}
				MQObject mqObject = new MQObject();
				mqObject.setId(row.stringValue("CONTAINER_ID"));
				mqObject.setName(row.stringValue("CONTAINER_NAME"));
				mqObject.setType(row.stringValue("CONTAINER_TYPE"));
				mqObject.setProperties(row.stringValue("CONTAINER_PROPERTIES"));
				result.getContainerList().add(mqObject);
			}
		}
		return result;
	}

	@Override
	public List<String> findFlowNameList(String appName, String flowType) {
		List<String> result = new ArrayList<String>();
		List<DataRow> records = this.skAppManage.findMFProfileRecords(appName, flowType);
		if (records != null){
			for (int i=0 ;i < records.size();i++){
				DataRow row = records.get(i);
				String messageFlowName = row.stringValue("MF_NAME");
				result.add(messageFlowName);
			}
		}
		return result;
	}

	@Override
	public List<PropertiesResource> findRawPropertiesRourceList() {
		List<PropertiesResource> result = new ArrayList<PropertiesResource>();
		List<String> propertieKeyList = skAppManage.findPropertiesKeyList();
		PropertiesResourceManager manager = PropertiesResourceManager.instance();
		HashMap<String,LinkedHashMap<String,String>> configs = manager.getPropertiesConfig();
		if (propertieKeyList != null && configs != null && configs.size() > 0){
			for (int i = 0;i < propertieKeyList.size();i++){
				String varCode = propertieKeyList.get(i);
				PropertiesResource propertiesResource = new PropertiesResource();
				propertiesResource.setCode(varCode);
				LinkedHashMap<String,String> configRow = configs.get(varCode);
				if (configRow != null && configRow.size() > 0){
					Iterator<String> keys = configRow.keySet().iterator();
					while (keys.hasNext()){
						String key = keys.next();
						propertiesResource.getPropertyKeyList().add(key);
					}
				}
				result.add(propertiesResource);
			}
		}
		return result;
	}
	

	@Override
	public List<TmpResourceGrp> retrieveTmpResGrpList() {
		List<TmpResourceGrp> resGrpList = new ArrayList<TmpResourceGrp>();
		List<DataRow> dataList = getService().findResGrpRecords(new DataParam());
		for (int i = 0; i < dataList.size(); i++) {
			TmpResourceGrp tmpResGrp = new TmpResourceGrp();
			DataRow dataRow = dataList.get(i);
			tmpResGrp.setGrpCode(dataRow.stringValue("CODE_ID"));
			tmpResGrp.setGrpName(dataRow.stringValue("CODE_NAME"));
			resGrpList.add(tmpResGrp);
		}
		return resGrpList;
	}

	@Override
	public List<TmpResource> retrieveTmpResList(String grpCode) {
		List<TmpResource> resList = new ArrayList<TmpResource>();
		List<DataRow> dataList = getService().findRecords(new DataParam("temptGrp", grpCode));
		for (int i = 0; i < dataList.size(); i++) {
			TmpResource tmpResource = new TmpResource();
			DataRow dataRow = dataList.get(i);
			tmpResource.setResId(dataRow.stringValue("TEMPT_ID"));
			tmpResource.setResName(dataRow.stringValue("TEMPT_NAME"));
			resList.add(tmpResource);
		}
		return resList;
	}
	
	protected TmpResourceManage getService() {
		return (TmpResourceManage) BeanFactory.instance().getBean("tmpResourceManageService");
	}
}